<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', '网关']" />
    <a-card class="general-card" title="网关">
      <formCom
        ref="formComDom"
        :option="searchOption"
        :key-count="state.keyCount"
        @serachFn="searchFn"
      />
      <div class="right-btn">
        <el-button plan type="primary" @click="actionFn('add', {})"
          >新增网关</el-button
        >
      </div>
      <kxTable
        :table-data="list"
        :column-list="columnList"
        border
        :loading="listLoading"
      >
        <template #options="{ row }">
          <el-button link plan type="primary" @click="actionFn('detail', row)"
            >详情</el-button
          >
          <el-button link type="primary" @click="actionFn('edit', row)"
            >编辑</el-button
          >
          <el-button link plan type="danger" @click="actionFn('del', row)"
            >删除</el-button
          >
          <el-button link type="primary" @click="actionFn('refresh', row)">
            刷新</el-button
          >
        </template>
      </kxTable>

      <Pagination
        v-model:limit="pageSize"
        v-model:page="currentPage"
        :total="total"
        @pagination="getList()"
        @pagination-size-change="getList(1)"
      />

      <!-- 新增网关弹框 -->
      <el-dialog
        v-model="showAddModal"
        :title="titleType[dialogType]"
        width="600px"
      >
        <!-- 使用 Tabs 切换详情和日志 -->
        <el-tabs v-model="activeDetailTab">
          <el-tab-pane label="详情" name="detail">
            <el-form :model="newItem" label-width="100px">
              <formCom
                ref="formComDom"
                :option="option"
                :key-count="state.keyCount"
                @submit-fn="submitFn"
                @cancle-fn="closeDialog"
              />
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="日志" name="log">
            <el-table :data="logData" border style="width: 100%">
              <el-table-column prop="date" label="日期" width="150" />
              <el-table-column
                prop="temperature"
                label="温度(°C)"
                width="120"
              />
              <el-table-column prop="humidity" label="湿度(%)" width="120" />
              <el-table-column prop="smoke" label="烟感" />
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="onCancel">取 消</el-button>
            <el-button type="primary" @click="onConfirm">确 定</el-button>
          </span>
        </template> -->
      </el-dialog>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { useList } from '@/use/index';
  import {
    gatewayListApi,
    gatewayAddApi,
    gatewayUpdateApi,
    gatewayDelApi,
  } from '@/utils/apiConfig';
  import { getQrcodeForType } from './table';
  import { setDeptFormatter } from '@/utils/util';
  const deptList = setDeptFormatter();
  const router = useRouter();
  const route = useRoute();
  const {} = route.query;
  const state = reactive({ keyCount: 1 });
  import { useUserStore } from '@/store';
  const userStore = useUserStore();
  const {
    searchForm,
    list,
    listLoading,
    total,
    currentPage,
    pageSize,
    getList,
    handleSearch,
    resetSearch,
  } = useList(gatewayListApi);
  if (!searchForm.value) {
    searchForm.value = {
      gatewayName: '', // 与后端搜索参数一致
      deptNo: '',
    } as any;
  }
  const dialogType = ref('add');
  const dialogItem = ref({});
  const titleType: any = {
    add: '新增网关',
    edit: '编辑网关',
    detail: '网关详情',
  };
  // Tab 状态：默认显示详情
  const activeDetailTab = ref('detail');
  // 日志数据
  const logData = ref([
    {
      date: '2022-09-09',
      temperature: 11,
      humidity: 22,
      smoke: '正常',
    },
    {
      date: '2022-09-09',
      temperature: 11,
      humidity: 22,
      smoke: '正常',
    },
    {
      date: '2022-09-09',
      temperature: 11,
      humidity: 22,
      smoke: '正常',
    },
  ]);
  const searchOption = reactive({
    labelWidth: '120px',
    isBetween: false,
    position: 'left',
    formList: [
      {
        label: '网关名称',
        val: '',
        field: 'gatewayName',
        type: 'input',
        width: '340px',
        rightMargin: true,
      },
      {
        label: '部门编号',
        val: '',
        field: 'deptNo',
        type: 'input',
        width: '340px',
        rightMargin: true,
      },
    ],
    showSreach: true,
  });
  const option = reactive({
    labelWidth: '100px',
    isBetween: false,
    showSubmit: true,
    position: 'left',
    formList: [
      {
        label: '网关编号',
        val: '',
        field: 'gatewayNo',
        type: 'input',
        width: '100%',
        require: true,
      },
      {
        label: '网关名称',
        val: '',
        field: 'gatewayName',
        type: 'input',
        width: '100%',

        require: true,
      },
      {
        label: '部门编号',
        val: '',
        field: 'deptNo',
        type: 'treeSelect',
        width: '100%',
        require: true,
        chooseList: deptList,
      },
      {
        label: '街道地址',
        val: '',
        field: 'street',
        type: 'input',
        width: '100%',
        require: true,
      },

      {
        label: '所属厂区',
        val: '',
        field: 'building',
        type: 'select',
        width: '100%',
        require: true,
        maxlength: 100,
        chooseList: userStore.workshopList,
      },
      {
        label: '详细地址',
        val: '',
        field: 'location',
        type: 'input',
        width: '100%',
        require: true,
      },
      {
        label: 'ip',
        val: '',
        field: 'ip',
        type: 'input',
        width: '100%',
        require: true,
      },
      {
        label: '端口',
        val: '',
        field: 'port',
        type: 'input',
        width: '100%',
        require: true,
      },
      {
        label: '位移传感器',
        val: '',
        field: 'qrCode',
        type: 'select',
        width: '100%',
        require: true,
        filterable: true,
        chooseList: getQrcodeForType(1),
        chooseListField: ['labelCode', 'id'],
      },
      {
        label: '状态',
        val: '',
        field: 'status',
        type: 'input',
        width: '100%',
      },
      {
        label: '备注',
        val: '',
        field: 'remark',
        type: 'input',
        width: '100%',
      },
    ],
  });

  const showAddModal = ref(false);
  const disabledArr = ['gatewayNo', 'lat', 'lon'];
  const columnList = reactive([
    { label: '网关编号', prop: 'gatewayNo', minWidth: '120px', disabled: true },
    { label: '网关名称', prop: 'gatewayName', minWidth: '120px' },
    { label: '部门编号', prop: 'deptNo', minWidth: '120px' },
    { label: '街道地址', prop: 'street', minWidth: '120px' },

    { label: '详细地址', prop: 'location', minWidth: '120px' },
    { label: 'ip', prop: 'ip', minWidth: '120px' },
    { label: '端口', prop: 'port', minWidth: '120px' },
    { label: '状态', prop: 'status', minWidth: '120px' },
    { label: '备注', prop: 'remark', minWidth: '120px' },
    { label: '经度', prop: 'lat', minWidth: '120px' },
    { label: '纬度', prop: 'lon', minWidth: '120px' },
    {
      slot: 'operation',
      width: '220',
      label: '操作',
      prop: 'options',
      notooltip: true,
      fixed: 'right',
    },
  ]);
  function inits() {}
  function searchFn(obj: any) {
    console.log('searchFn', obj);
    searchForm.value = { ...(searchForm.value || {}), ...obj };
    getList();
  }
  function closeDialog() {
    showAddModal.value = false;
    option.formList.forEach((item) => {
      item.val = '';
    });
    state.keyCount += 1;
  }
  function submitFn(obj: any) {
    console.log(111111, obj);
    // list.value.push(obj);

    switch (dialogType.value) {
      case 'add':
        gatewayAddApi(obj)
          .then((res) => {
            console.log('add-res', res);
            getList();
            ElMessage({
              message: '新增网关成功',
              type: 'success',
            });
          })
          .catch((err) => {
            console.log('add-err', err);
          });
        break;

      case 'edit':
        const roomNo = dialogItem.value?.roomNo;

        gatewayUpdateApi({ ...obj, roomNo })
          .then((res) => {
            console.log('update-res', res);
            getList();
            ElMessage({
              message: '更新网关成功',
              type: 'success',
            });
          })
          .catch((err) => {
            console.log('update-err', err);
          });
        break;
      case 'detail':
        break;
      default:
        break;
    }

    closeDialog();
  }

  // 弹框与表单

  const addFormRef = ref<FormInstance>();
  const newItem = ref({
    departmentName: '',
    departmentType: '',
    desc: '',
    tag: '',
  });

  function actionFn(type: string, item: any) {
    console.log(type, item);
    dialogType.value = type;
    dialogItem.value = item;
    switch (type) {
      case 'detail':
        activeDetailTab.value = 'detail';
        option.showSubmit = false;
        option.formList.forEach((one) => {
          one.val = item[one.field];
          one.disabled = true;
        });
        state.keyCount += 1;
        showAddModal.value = true;
        break;
      case 'add':
        option.formList.forEach((one) => {
          one.val = '';
        });

        activeDetailTab.value = 'detail';
        showAddModal.value = true;
        state.keyCount += 1;
        break;
      case 'del':
        console.log(item.departmentName);
        ElMessageBox.confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('del-api');
            const gatewayNo = item?.gatewayNo;
            gatewayDelApi({ addPath: gatewayNo })
              .then((res) => {
                console.log('del-res', res);
                getList();
                ElMessage({
                  message: '删除网关成功',
                  type: 'success',
                });
              })
              .catch((err) => {
                console.log('del-err', err);
              });
          })
          .catch(() => {});
        break;

      case 'edit':
        activeDetailTab.value = 'detail';

        option.showSubmit = true;
        option.formList.forEach((one) => {
          one.val = item[one.field];
          if (disabledArr.includes(one.field)) {
            one.disabled = true;
          } else {
            one.disabled = false;
          }
        });
        state.keyCount += 1;
        showAddModal.value = true;
        break;
      case 'refresh':
        alert('刷新传感器');
        break;
      default:
        break;
    }
  }
  onMounted(() => {
    inits();
    getList();
  });
</script>

<style lang="less" scoped>
  .container {
    padding: 20px;
  }
</style>
